package service

import (
	"strconv"
	"time"

	"im/dao"
	"im/model"
)

type GroupService interface {
	DeleteByID(appsId uint, id int64, user model.Users) error
	UpdateById(id int64, param model.GroupsCreatable) error
	Create(user model.Users, data model.GroupsCreatable) (model.Groups, error)
	GetById(groupId int64) (model.Groups, error)
}

func NewGroupService() GroupService {
	return &groupService{d: dao.NewGroupsDaoWithEs()}
}

type groupService struct {
	d dao.GroupsDao
}

func (r groupService) DeleteByID(appsId uint, id int64, user model.Users) error {
	err := r.d.DeleteById(id, user.Id)
	if err != nil {
		return err
	}
	err = NewRongYun().DismissGroup(id, strconv.FormatInt(user.Id, 10))
	return err
}

func (r groupService) Create(user model.Users, data model.GroupsCreatable) (model.Groups, error) {
	group, err := r.d.Create(user, data)
	if err != nil {
		return group, err
	}
	err = NewRongYun().CreateGroup(group.Id, data.Name, strconv.FormatInt(user.Id, 10))
	if err != nil {
		return group, err
	}
	// 把用户添加到群组用户中去
	ruModel := &model.GroupsUsers{AppsId: user.AppsId, GroupId: group.Id, UserId: user.Id, Role: model.GROUP_USER_ROLE_IS_OWNER, Status: 1, Joined: time.Now(), GroupsUsersModifiable:
	model.GroupsUsersModifiable{
		PostsNotify: 1,
		Nickname:    user.Nickname,
	}}
	err = NewGroupUsersService().Create(ruModel)

	if err != nil {
		return group, err
	}
	err = NewRongYun().JoinGroup(group.Id, group.Name, strconv.FormatInt(user.Id, 10))

	// 更新帖子中的group信息
	groupIds, err := dao.NewGroupsUsersDao().GetGroupIdListByUserId(group.UserId)
	if err != nil {
		return group, err
	}
	err = dao.NewPostsWithEs().UpdateGroup(group.UserId, groupIds...)

	return group, err
}

func (r groupService) UpdateById(id int64, param model.GroupsCreatable) error {
	err := r.d.UpdateById(id, param)
	if err != nil {
		return err
	}
	if param.Name != "" {
		err = NewRongYun().RefreshGroup(id, param.Name)
	}
	return err
}
func (r groupService) GetById(groupId int64) (model.Groups, error) {
	row := model.Groups{}
	row, err := r.d.GetById(groupId)
	return row, err

}
